﻿using System;
using Microsoft.CodeMarkers.Internal;

namespace Microsoft.CodeMarkers
{
    public static class CodeMarker
    {
        internal static CodeMarkerServiceHost ServiceHost { get; set; }
        internal static CodeMarkerClientHost ClientHost { get; set; }

        public static void Raise<TEnum>(TEnum marker)
        {
            CodeMarkerServiceHost s = InitializeServiceHost();
            
            if (s != null)
            {
                s.Raise(Convert.ToInt32(marker));
            }
        }

        public static void InitializeService()
        {
            InitializeServiceHost();
        }

        public static void InitializeClient<TEnum>(int targetProcessId)
        {
            ClientHost = new CodeMarkerClientHost(targetProcessId);
        }

        public static void WaitFor<TEnum>(TimeSpan timeout, params TEnum[] markers)
        {
            using (new CodeMarkerWaiter<TEnum>(timeout, markers)) { }
        }

        public static void FreeResources()
        {
            CodeMarkerClientHost c = ClientHost;

            if (c != null)
            {
                c.Dispose();
                ClientHost = null;
            }

            CodeMarkerServiceHost s = ServiceHost;

            if (s != null)
            {
                s.Dispose();
                ServiceHost = null;
            }
        }

        private static CodeMarkerServiceHost InitializeServiceHost()
        {
            CodeMarkerServiceHost newService = ServiceHost;

            if (newService == null)
            {
                newService = new CodeMarkerServiceHost();
                newService.StartServer();
                ServiceHost = newService;
            }

            return newService;
        }
    }
}
